'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { use } from 'react';
import dynamic from 'next/dynamic';
import toast from 'react-hot-toast';
import '@uiw/react-md-editor/markdown-editor.css';
import '@uiw/react-markdown-preview/markdown.css';

// 动态导入Markdown编辑器以避免SSR问题
const MDEditor = dynamic(
  () => import('@uiw/react-md-editor').then((mod) => mod.default),
  { ssr: false }
);

interface DocumentFormData {
  title: string;
  content: string;
  published: boolean;
}

export default function EditDocumentPage({ params }: { params: { id: string } }) {
  const resolvedParams = use(params);
  const router = useRouter();
  const isNew = resolvedParams.id === 'new';
  const [loading, setLoading] = useState(!isNew);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [formData, setFormData] = useState<DocumentFormData>({
    title: '',
    content: '',
    published: false,
  });

  useEffect(() => {
    if (!isNew) {
      fetchDocument();
    }
  }, [isNew]);

  const fetchDocument = async () => {
    try {
      const response = await fetch(`/api/documents/${resolvedParams.id}`);
      if (!response.ok) {
        throw new Error('获取文档失败');
      }
      const data = await response.json();
      setFormData(data);
    } catch (err) {
      setError('获取文档失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 表单验证
    if (!formData.title.trim()) {
      toast.error('请输入文档标题');
      return;
    }
    if (!formData.content.trim()) {
      toast.error('请输入文档内容');
      return;
    }

    setSaving(true);

    try {
      const url = isNew ? '/api/documents' : `/api/documents/${resolvedParams.id}`;
      const method = isNew ? 'POST' : 'PUT';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        throw new Error('保存文档失败');
      }

      toast.success('保存成功');
      router.push('/documents');
    } catch (err) {
      toast.error('保存文档失败');
      setError('保存文档失败');
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <div className="p-4">加载中...</div>;
  if (error) return <div className="p-4 text-red-500">{error}</div>;

  return (
    <div className="p-4 max-w-4xl mx-auto">
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <input
            type="text"
            value={formData.title}
            onChange={(e) => setFormData({ ...formData, title: e.target.value })}
            placeholder="文档标题"
            className="w-full px-4 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          />
        </div>

        <div data-color-mode="light">
          <MDEditor
            value={formData.content}
            onChange={(value) => setFormData({ ...formData, content: value || '' })}
            height={400}
            preview="edit"
          />
        </div>

        <div className="flex items-center gap-2">
          <label className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={formData.published}
              onChange={(e) => setFormData({ ...formData, published: e.target.checked })}
              className="rounded text-blue-500 focus:ring-blue-500"
            />
            <span>发布</span>
          </label>
        </div>

        <div className="flex gap-4">
          <button
            type="submit"
            disabled={saving}
            className="bg-blue-500 text-white px-6 py-2 rounded hover:bg-blue-600 disabled:opacity-50"
          >
            {saving ? '保存中...' : '保存'}
          </button>
          <button
            type="button"
            onClick={() => router.back()}
            className="px-6 py-2 border rounded hover:bg-gray-100"
          >
            取消
          </button>
        </div>
      </form>
    </div>
  );
}